package org.tio.sitexxx.service.service.atom;

import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.sitexxx.service.cache.CacheConfig;
import org.tio.sitexxx.service.cache.Caches;
import org.tio.sitexxx.service.model.main.User;
import org.tio.sitexxx.service.service.base.RegisterService;
import org.tio.sitexxx.service.service.base.UserService;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;

public class RegisterAtom extends AbsAtom {

	private static Logger	log	= LoggerFactory.getLogger(RegisterAtom.class);
	private User			user;

	public RegisterAtom(User user) {
		this.user = user;
	}

	@Override
	public boolean run() throws SQLException {
		if (RegisterService.me.isLoginnameExists(user.getLoginname())) {
			msg = "该账号已注册，如忘记密码，请找回";
			log.error(msg + ",loginname:{},nick:{},pwd:{}", user.getLoginname(), user.getNick(), user.getPwd());
			return false;
		}
		String nick = user.getNick();
		String initNick = nick;

		while (RegisterService.me.isNickExists(nick)) {
			nick += RandomUtil.randomString(RandomUtil.BASE_CHAR, 2);
			msg = "您的昵称【" + initNick + "】已经存在，平台已为您生成新的昵称【" + nick + "】，您登录后可在个人中心进行昵称修改，谢谢！";
		}
		user.setNick(nick);

		if (UserService.ME.save(user) == null) {
			msg = "账号注册失败：账号信息有误";
			log.error(msg + ",loginname:{},nick:{},pwd:{}", user.getLoginname(), user.getNick(), user.getPwd());
			return false;
		}

		user.update();

		boolean roleResult = RegisterService.me.initRole(user);
		if (!roleResult) {
			msg = "账号注册失败：角色数据初始化失败";
			log.error(msg + ",loginname:{},nick:{},pwd:{}", user.getLoginname(), user.getNick(), user.getPwd());
			return false;
		}

		//清空当前用户数
		Caches.getCache(CacheConfig.USER_COUNT).clear();

		if (StrUtil.isBlank(msg)) {
			msg = "注册成功";
		}
		return true;
	}

}
